<template>
  <div>
    <div class="fd-nav">
      <div class="fd-nav-left">
        <span style="margin-left:40px;margin-right:20px">审批类型</span>
        <el-select v-model="flowType" placeholder="请选择流程类型" style="width: 160px" @change="selectType">
          <el-option v-for="item in flowTypeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <span style="margin-left:40px;margin-right:20px">发起人ID：  {{ userId }}</span>
        <span style="margin-left:40px;margin-right:20px">发起人名称：{{ userName }}</span>
      </div>

      <div class="fd-nav-right">
        <button v-show="!isPreview && newVersion==version && newVersion>0 " type="button" class="ant-btn button-publish" @click="preview"><span>预 览</span></button>
        <button v-show="isPreview" type="button" class="ant-btn button-publish" @click="selectuser"><span>选择发起人</span></button>
        <button v-show="isPreview" type="button" class="ant-btn button-publish" @click="notpreview"><span>退出预览</span></button>
        <button v-show="!isPreview" type="button" class="ant-btn button-publish" @click="saveSet"><span>保 存</span></button>
        <button v-show="!isPreview" type="button" class="ant-btn button-publish" @click="pre"><span>上个版本</span></button>
        <span v-show="!isPreview">当前版本：{{ version }}</span>
        <span v-show="!isPreview" style="margin-left:10px">最新版本：{{ newVersion }}</span>
        <button v-show="!isPreview" type="button" class="ant-btn button-publish" @click="next"><span>下个版本</span></button>
      </div>
    </div>
    <!-- 页面大小控制 -->
    <div class="fd-nav-content">
      <section class="dingflow-design">
        <div class="zoom">
          <div :class="'zoom-out'+ (nowVal==50?' disabled':'')" @click="zoomSize(1)" />
          <span>{{ nowVal }}%</span>
          <div :class="'zoom-in'+ (nowVal==300?' disabled':'')" @click="zoomSize(2)" />
        </div>
        <div id="box-scale" class="box-scale" :style="'transform: scale('+nowVal/100+'); transform-origin: 50% 0px 0px;'">
          <nodeWrap
            :node-config.sync="nodeConfig"
            :is-tried.sync="isTried"
            :director-max-level="directorMaxLevel"
            :table-id="tableId"
          />
          <div class="end-node">
            <div class="end-node-circle" />
            <div class="end-node-text">流程结束</div>
          </div>
        </div>
      </section>
    </div>
    <el-dialog title="提示" :visible.sync="tipVisible">
      <div class="ant-confirm-body">
        <i class="anticon anticon-close-circle" style="color: #f00;" />
        <span class="ant-confirm-title">当前无法发布</span>
        <div class="ant-confirm-content">
          <div>
            <p class="error-modal-desc">以下内容不完善，需进行修改</p>
            <div class="error-modal-list">
              <div v-for="(item,index) in tipList" :key="index" class="error-modal-item">
                <div class="error-modal-item-label">流程设计</div>
                <div class="error-modal-item-content">{{ item.name }} 未选择{{ item.type }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="tipVisible = false">我知道了</el-button>
        <el-button type="primary" @click="tipVisible = false">前往修改</el-button>
      </span>
    </el-dialog>

    <!--选择发起人对话框  -->
    <el-dialog :close-on-click-modal="false" title="选择发起人" :visible.sync="sponsorVisible" width="600px" append-to-body class="promoter_person">
      <div class="person_body clear">
        <div class="person_tree l">
          <el-tabs>
            <el-tab-pane label="组织架构" name="1" />
          </el-tabs>

          <ul style="height: 360px;">
            <li v-for="(item,index) in departments.deptList" :key="index+'b'" class="check_box not">
              <a><img src="@/assets/images/flow/icon_file.png">{{ item.deptName }}</a>

              <i @click="getDownDept(item)">下级</i>
              <i @click="getDeptListUP()">上级</i>
            </li>
            <li v-for="(item,index) in departments.userList" :key="index+'c'" class="check_box">
              <a :class="toggleClass(sponsorList,item)&&'active'" :title="item.departmentNames" @click="toChecked(sponsorList,item)">
                <img src="@/assets/images/flow/icon_people.png">{{ item.userName }}</a>
              <i @click="getDeptListUP()">上级</i>
            </li>
          </ul>
        </div>
        <div class="has_selected l">
          <p class="clear">已选（{{ sponsorList.length }}）
            <a @click="sponsorList=[];">清空</a>
          </p>
          <ul>
            <li v-for="(item,index) in sponsorList" :key="index+'e1'">
              <img src="@/assets/images/flow/icon_people.png">
              <span>{{ item.userName }}</span>
              <img src="@/assets/images/flow/cancel.png" @click="removeEle(sponsorList,item)">
            </li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sponsorVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSponsor">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { findUserAndDept } from '@/api/system/user'
import { add, getFlow, matchTest } from '@/api/flow/flow'
export default {
  name: 'Flow',

  data() {
    return {
      isTried: false,
      tipList: [],
      tipVisible: false,
      nowVal: 100,
      nodeConfig: {
        nodeName: '发起人',
        type: 0,
        priorityLevel: '',
        settype: '',
        selectMode: '',
        selectRange: '',
        examineRoleId: '',
        directorLevel: '',
        replaceByUp: '',
        examineMode: '',
        noHanderAction: '',
        examineEndType: '',
        examineEndRoleId: '',
        examineEndDirectorLevel: '',
        ccSelfSelectFlag: '',
        conditionList: [],
        nodeUserList: [],
        childNode: null,
        conditionNodes: []
      },
      depts: '',
      workFlowDef: {},
      directorMaxLevel: 0,
      dialogVisible: true,
      tableId: '',
      flowTypeList: [
        {
          'id': 1,
          'name': '转正'
        },
        {
          'id': 2,
          'name': '转岗'
        },
        {
          'id': 3,
          'name': '离职'
        }
      ],
      pidUPlist: [],
      departments: [],
      sponsorVisible: false,
      sponsorList: [],
      flowType: '',
      newVersion: '',
      version: '',
      isPreview: false,
      userId: '',
      userName: ''

    }
  },
  created() {

  },

  methods: {
    //  初始查询流程
    initFlow() {
      const param = {
        tempType: this.flowType,
        version: this.version
      }
      getFlow(param).then(res => {
        if (res.data === null) {
          this.nodeConfig = {
            nodeName: '发起人',
            type: 0
          }
          this.version = 0
          this.newVersion = 0
        } else {
          this.nodeConfig = res.data
          this.version = res.data.version
          this.newVersion = res.data.version
        }
      })
    },
    //  第二次以后的查询流程
    findFlow() {
      const param = {
        tempType: this.flowType,
        version: this.version
      }
      getFlow(param).then(res => {
        if (res.data === null) {
          this.nodeConfig = {
            nodeName: '发起人',
            type: 0
          }
          this.version = 0
          this.newVersion = 0
        } else {
          this.nodeConfig = res.data
          this.version = res.data.version
        }
      })
    },
    // 递归获取各个节点的数据
    reErr(data) {
      if (data.childNode) {
        if (data.childNode.type === 1) { // 审批人
          if (data.childNode.error) {
            this.tipList.push({ name: data.childNode.nodeName, type: '审核人' })
          }
          this.reErr(data.childNode)
        } else if (data.childNode.type === 2) { // 抄送人
          if (data.childNode.error) {
            this.tipList.push({ name: data.childNode.nodeName, type: '抄送人' })
          }
          this.reErr(data.childNode)
        } else if (data.childNode.type === 3) { // 大条件
          this.reErr(data.childNode.childNode)
        } else if (data.childNode.type === 4) { // 小条件
          this.reErr(data.childNode)
          for (var i = 0; i < data.childNode.conditionNodes.length; i++) {
            if (data.childNode.conditionNodes[i].error) {
              this.tipList.push({ name: data.childNode.conditionNodes[i].nodeName, type: '条件' })
            }
            this.reErr(data.childNode.conditionNodes[i])
          }
        }
      } else {
        data.childNode = null
      }
    },
    // 选择审批类型
    selectType() {
      this.version = ''
      this.initFlow()
    },
    // 选择发起人
    selectuser() {
      this.sponsorVisible = true
      this.getInitDeptList()
    },

    // 预览
    preview() {
      if (this.flowType === '') {
        this.$message.info('请选择类型!')
      } else {
        this.isPreview = true
      }
    },
    sureSponsor() {
      const params = {
        userId: this.userId,
        tempType: this.flowType,
        version: this.version
      }
      matchTest(params).then(res => {
        this.sponsorVisible = false
        if (res.code === 20000) {
          this.$message.success('匹配成功!')
          // 刷新页面
          this.nodeConfig = res.data
          this.newVersion = res.data.version
          this.version = res.data.version
        }
      })
    },
    // 退出预览
    notpreview() {
      this.isPreview = false
      this.sponsorList = []
      this.userId = ''
      this.userName = ''
      this.findFlow()
    },
    // 上个版本
    pre() {
      if (this.version > 1) {
        this.version--
        this.findFlow()
      } else {
        this.$message.info('已经是最老版本了!')
      }
    },
    // 下个版本
    next() {
      if (this.version < this.newVersion) {
        this.version++
        this.findFlow()
      } else {
        this.$message.info('已经是最新版本了!')
      }
    },

    // 保存版本
    saveSet() {
      this.$confirm('是否确认保存, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        this.isTried = true
        this.tipList = []
        this.reErr(this.nodeConfig)
        if (this.tipList.length !== 0) {
          this.tipVisible = true
          return
        }
        if (this.flowType === '') {
          this.$message.error('请先选择类型!')
          return
        }

        this.nodeConfig.tempType = this.flowType

        add(this.nodeConfig).then(res => {
          if (res.code === 20000) {
            this.$message.success('保存成功!')
            // 刷新页面
            location.reload()
          }
        })
      })

      // console.log(JSON.stringify(this.processConfig.nodeConfig))
    },
    zoomSize(type) {
      if (type === 1) {
        if (this.nowVal === 50) {
          return
        }
        this.nowVal -= 10
      } else {
        if (this.nowVal === 300) {
          return
        }
        this.nowVal += 10
      }
    },

    // 第一级下的部门和员工
    getInitDeptList() {
      const params = {
        deptId: 0
      }
      findUserAndDept(params).then(res => {
        if (res.code === 20000) {
          this.departments = res.data
        }
      })
    },
    // 上级 部门和员工
    getDeptListUP() {
      if (this.pidUPlist.length > 0) {
        const params = {
          deptId: this.pidUPlist.pop()
        }
        findUserAndDept(params).then(res => {
          if (res.code === 20000) {
            this.departments = res.data
          }
        })
      } else {
        this.$message.info('已经是最顶级了!')
      }
    },

    // 下级的部门
    getDownDept(dept, ctype) {
      const params = {
        deptId: dept.id
      }
      if (ctype === 101) {
        findUserAndDept(params).then(res => {
          if (res.code === 20000) {
            if (res.data.deptList.length === 0) {
              this.$message.info('已经是最低级了!')
            } else {
              this.pidUPlist.push(dept.pid)
              this.departments = res.data
            }
          }
        })
      } else {
        findUserAndDept(params).then(res => {
          if (res.code === 20000) {
            if (res.data.deptList.length === 0 && res.data.userList.length === 0) {
              this.$message.info('已经是最低级了!')
            } else {
              this.pidUPlist.push(dept.pid)
              this.departments = res.data
            }
          }
        })
      }
    },
    // 判断是否包含，来动态添加样式
    toggleClass(arr, elem, key = 'id') {
      return arr.some(item => { return item[key] === elem[key] })
    },

    // 勾选用户，只能选择一个
    toChecked(arr, elem, key = 'id') {
      if (arr.length === 0) {
        this.userId = elem.id
        this.userName = elem.userName
        const isIncludes = this.toggleClass(arr, elem, key)
        !isIncludes ? arr.push(elem) : this.removeEle(arr, elem, key)
      } else if (arr.length === 1) {
        if (arr[0].id === elem.id) {
          this.userId = elem.id
          this.userName = elem.userName
          const isIncludes = this.toggleClass(arr, elem, key)
          !isIncludes ? arr.push(elem) : this.removeEle(arr, elem, key)
        } else {
          this.$message.info('只能选择一个用户!')
        }
      } else {
        this.$message.info('只能选择一个用户!')
      }
    },

    // 取消勾选的部门活员工
    removeEle(arr, elem, key = 'id') {
      var includesIndex
      arr.map((item, index) => {
        if (item[key] === elem[key]) {
          includesIndex = index
        }
      })
      arr.splice(includesIndex, 1)
    }
  }
}
</script>
<style>
@import "../../../assets/css/workflow.css";
.error-modal-list {
	width: 455px;
}
</style>
